package edu.je.zuul.filter;

import com.alibaba.fastjson.JSONObject;
import com.junqson.je.common.constant.AppConstant;
import com.junqson.je.common.constant.AppRedisKey;
import com.junqson.je.common.exception.BizException;
import com.junqson.je.common.model.ApiResult;
import com.junqson.je.common.util.AppUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import edu.je.zuul.client.UserClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;

@Slf4j
public class AuthFilter extends ZuulFilter{
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserClient userClient;

    @Override
    public String filterType(){
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    //控制过滤器生效不生效，可以在里面写一串逻辑来控制
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //执行过滤逻辑
    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        String token = request.getHeader(AppConstant.AUTH_HEADER);

        String userId = null;
        if (StringUtils.isNotEmpty(token)) {
            String tokenK = AppUtil.getRedisKey(AppRedisKey.TOKEN, token);
            userId = stringRedisTemplate.opsForValue().get(tokenK);
            if (StringUtils.isNotEmpty(userId)) {
                log.info("token: {}, userId: {}", token, userId);
                // 检查缓存
                String userK = AppUtil.getRedisKey(AppRedisKey.USER_CACHE, userId);
                if (redisTemplate.opsForValue().get(userK) == null) {
                    ApiResult result = userClient.loadUser(Integer.valueOf(userId));
                    if (!result.isSuccess()) {
                        context.setSendZuulResponse(false);
                        ApiResult apiResult = ApiResult.error(1,"用户服务异常");
                        context.setResponseBody(JSONObject.toJSONString(apiResult));
                        context.getResponse().setContentType("application/json; charset=utf-8");
                        return null;
                    }
                }
                final String finalUid = userId;
                context.addZuulRequestHeader(AppConstant.UID_HEADER,finalUid);

            }
        }
        return null;
    }

}


